import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import {
  cancelGive,
  confirmGive,
  getCouponDetail,
  getCardDetail,
  getCouponReceiveCode,
  getCouponStatus,
  getCouponSyncConfig,
  getPrototypeInfo,
  getCouponPrototype,
  receiveBizCouponNew
} from "@src/api/coupon";
import { getCouponDetailNew } from '@src/api/member';
import $color from "@src/common/color";
import dayjs from "dayjs";
import pageHandleUtil from "@src/common/pageHandleUtil";
import base from "@src/store/base";
import router from '@src/router'
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['businessName', 'businessLogo', 'themeColor', 'themeTitleColor']
  }],
  properties: {

  },
  data: {
    navHeight: 80,
    couponStatus: null,
    couponDetail: null,
    //是否过期
    isExpired: false,
    qrNumber: '',
    pageBgColor: {},
    eanCode: "",
    qrCode: "",
    //使用时间
    couponInstructionArr: [],
    couponCode: null,
    //卡的code
    code: null,
    //起始时间
    effectiveTime: null,
    //结束时间
    expireTime: null,
    //券原型
    prototype: null,
    touchX: 0,
    touchY: 0,
    showDetail: false,
    //按钮配置信息
    functionButtonConfig: null,
    //券状态，1：正常，2：已使用，3：已过期，4：已锁定
    status: 1,
    interTime: null,
    // 1.券 2.卡
    type: 1,
    //1 详情页  2.扫码领取页
    model: 1,
    loading: true,
    //核销商户
    verifyMerchant: "",
    //核销门店
    verifyShop: "奶茶店",
    businessName: "",
    businessLogo: "",
    //扫码领取页面展示信息的code
    receiveCode: "87ac8185802c405a98e7db62ab38c41c",
    //轮询的定时器
    setIntervalResult: null,
    //券的主题色
    theme: null,
    //券的字体颜色
    colorTitle: null,
    height: 0,
    availableTime: null
  },
  methods: {
    //此页面要兼容根据id查详情，根据code查券详情，以及扫码的receiveCode查详情
    onLoad(option) {
      console.log('option', option);
      if (option.type) {
        if (option.type == 2) {
          this.setData({ code: option.code })
        } else if (option.type == 1) {
          this.setData({ couponCode: option.couponCode })
        }
        this.setData({ type: option.type, })
      }
      if (option.receiveCode) { this.setData({ receiveCode: option.receiveCode, model: 2 }) }
      if (option.prototypeId) { this.setData({ prototypeId: option.prototypeId, model: 2 }) }
      // 禁用右上角转发
      wx.hideShareMenu();
    },
    onShow() {
    },
    onHide() {
      this.clear();
    },
    onUnload() {
      this.clear();
    },
    // 转发给微信好友(不能写到method里)
    onShareAppMessage(res) {
      wx.showShareMenu({ withShareTicket: true });
      if (res.from === "button") {
        this.setData({ sendFriendModal: false })
        this.confirmGiveReq();
      }
      return {
        title: "送你一张优惠券，点击消息立即领取。",
        path: `pages/receiveCoupon/main?receiveCode=${this.data.receiveCode}`,
        imageUrl: this.data.shareImg
      };
    },
    onLogin() {
      this.setData({ login: true });
      console.log("this.data.type", this.data.type);
      let self = this;
      //这里分扫码领券进来和详情页  model：1详情页 2为model页面
      if (this.data.model == 1) {
        console.log("列表进来");
        if (this.data.type == 1) {
          this.couponDetailReq().then(() => {
            // this.receiveCodeReq();
            if (self.data.couponStatus === 1 && !self.data.interTime) {
              let interTime = setInterval(() => {
                self.couponStatusReq();
              }, 5000)
              self.setData({ interTime: interTime })
            }
          })
        } else if (this.data.type == 2) {
          this.getCardDetailFunc()
        }
      } else {//扫码领券进来
        console.log('扫码领券进来');
        if (this.data.prototypeId) { this.getCouponPrototypeFunc() }
        else { this.getPrototypeInfoFunc() }
      }
      this.setData({ height: wx.getSystemInfoSync().windowHeight })
    },
    // 券的详情
    couponDetailReq() {
      let data = { couponCode: this.data.couponCode };
      return getCouponDetailNew(data).then(res => {
        if (res.code == 0) {
          let { status, availableTime, eanCode, qrCode, prototype, effectiveTime, expireTime } = res.data;
          // 时段可使用渲染
          let couponInstructionArr = {};
          //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
          if (availableTime && availableTime.timeType != 5) {
            // console.log('availableTime', availableTime)
            // console.log('availableTime.availablePeriod', availableTime.availablePeriod)
            // if (availableTime || availableTime.availablePeriod || availableTime.dateList) {
            console.log('availableTime.timeType', availableTime.timeType)
            if (availableTime.timeType == 1) {//领券后N天可用
              couponInstructionArr = { returnString: "领券后" + availableTime.days + "天可用", timeString: [] }
            } else if (availableTime.timeType == 2) {//规则星期可用
              couponInstructionArr = pageHandleUtil.dillCouponWeek([], false, availableTime);
            } else if (availableTime.timeType == 3) {//规则日期可用
              console.log('availableTime.timeType === 3', availableTime.timeType === 3)
              couponInstructionArr = pageHandleUtil.dillCouponDay([], false, availableTime);
            } else if (availableTime.timeType == 4) {//不规则日期可用
              let timeString = pageHandleUtil.mToStrArray(availableTime);
              // let returnString = availableTime.dateList.replace(/:/g, " ~ ");
              let returnString = '';
              let dateString=availableTime.dateList.replace(/:/g, " ~ ").split(',')
              timeString=dateString.concat(timeString)
              couponInstructionArr = { returnString: returnString, timeString: timeString }
            }
            //  }
          } else {
            couponInstructionArr = { returnString: `全部时段可用`, timeString: `` };
          }
          if (status !== 1) {
            this.setData({
              showDetail: true
            })
          } else {
            this.setData({
              showDetail: false,
            })
            if (this.data.setIntervalResult) {
              console.log("释放定时器")
              clearInterval(this.data.setIntervalResult);
              this.setData({ setIntervalResult: null })
            }
          }
          if (status === 5 && !this.data.setIntervalResult) {
            let setIntervalResult = setInterval(() => {
              return this.couponDetailReq();
            }, 1000);
            this.setData({ setIntervalResult })
          }
          console.log('couponInstructionArr', couponInstructionArr);
          console.log("eanCode", eanCode)
          this.setData({
            couponInstructionArr,
            // qrNumber,
            //couponStatus: 2,
            couponStatus: status,
            // status,
            effectiveTime,
            expireTime,
            eanCode,
            qrCode,
            loading: false,
            availableTime,
            // pageBgColor,
            prototype
          });
          if (status === 2) {
            this.couponStatusReq()
          }
          this.resetDescFunc()
          let theme, colorTitle;
          if (prototype.theme) {
            theme = prototype.theme;
            console.log('theme', theme)
            colorTitle = $color.getTitleColor(theme.toLowerCase());
          } else { theme = this.data.themeColor; colorTitle = this.data.themeTitleColor }
          this.setData({ theme, colorTitle })
          wx.setBackgroundColor({ backgroundColorTop: theme, backgroundColorBottom: theme });
          this.handleButtonConfig();
          this.handleTimeConfig()
        }
      })
    },
    //获取卡详情
    getCardDetailFunc() {
      let code = this.data.code;
      console.log('code', code)
      getCardDetail(code).then(res => {
        let { status, businessName, businessLogo, availableTime, eanCode, qrCode, prototype, effectiveTime, expireTime, leftAmount } = res.data;
        console.log('卡详情res', res);
        // 时段可使用渲染
        let couponInstructionArr = {};
        //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
        if (availableTime && availableTime.timeType != 5) {
          // console.log('availableTime', availableTime)
          // console.log('availableTime.availablePeriod', availableTime.availablePeriod)
          // if (availableTime.availablePeriod || availableTime.dateList) {
          if (availableTime.timeType == 1) {//领券后N天可用
            couponInstructionArr = { returnString: "领卡后" + availableTime.days + "天可用", timeString: [] }
          } else if (availableTime.timeType == 2) {//规则星期可用
            couponInstructionArr = pageHandleUtil.dillCouponWeek([], false, availableTime);
          }
          else if (availableTime.timeType == 3) {//规则日期可用
            console.log('availableTime.timeType === 3', availableTime.timeType === 3)
            couponInstructionArr = pageHandleUtil.dillCouponDay([], false, availableTime);
          }
          else if (availableTime.timeType == 4) {//不规则日期可用
            let timeString = pageHandleUtil.mToStrArray(availableTime);
            // let returnString = availableTime.dateList.replace(/:/g, " ~ ");
            let returnString = '';
            let dateString=availableTime.dateList.replace(/:/g, " ~ ").split(',')
            timeString=dateString.concat(timeString)
            couponInstructionArr = { returnString: returnString, timeString: timeString }
          }
          //   }
        } else {
          couponInstructionArr = { returnString: `全部时段可用`, timeString: `` };
        }
        if (status !== 1) {
          this.setData({
            showDetail: true
          })
        }
        console.log('couponInstructionArr', couponInstructionArr);
        console.log("eanCode", eanCode)
        this.setData({
          couponInstructionArr,
          businessName,
          businessLogo,
          couponStatus: status,
          // status,
          effectiveTime,
          expireTime,
          eanCode,
          qrCode,
          loading: false,
          leftAmount,
          prototype
        });
        let theme, colorTitle;
        if (prototype.theme) {
          theme = prototype.theme;
          colorTitle = $color.getTitleColor(theme.toLowerCase());
        } else { theme = this.data.themeColor; colorTitle = this.data.themeTitleColor }
        this.setData({ theme, colorTitle })
        wx.setBackgroundColor({ backgroundColorTop: theme, backgroundColorBottom: theme });
        if (status === 2) {
          this.couponStatusReq()
        }
        this.handleButtonConfig();
        this.handleTimeConfig();
      })
    },
    //组装券描述
    resetDescFunc() {
      let prototype = this.data.prototype;
      let desc = prototype.description;
      //如果是折扣券，组装优惠金额上限
      if (prototype.couponType === 'discount' && prototype.discountMaximum > 0) {
        if (desc) {
          desc = desc + `,最多可优惠${prototype.discountMaximum / 100}元`;
        } else {
          desc = `最多可优惠${prototype.discountMaximum / 100}元`;
        }

        this.setData({ 'prototype.description': desc });
      }
    },
    //通过卡券id查询原型数据
    getCouponPrototypeFunc() {
      let prototypeIds = [];
      prototypeIds.push(this.data.prototypeId);
      getCouponPrototype(prototypeIds).then(res => {
        if (res.code == 0) {
          let data = res.data[0];
          let availableTime = data.detail.availableTime;
          let prototype = data.detail.prototype;
          let receiveCode = prototype.receiveCode  //解决其他页面进来无receiveCode情况 （20220422森）
          // 时段可使用渲染
          let couponInstructionArr = {};
          //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
          if (availableTime && availableTime.timeType != 5) {

            //    if (availableTime.availablePeriod || availableTime.dateList) {
            console.log('availableTime.timeType', availableTime.timeType)
            if (availableTime.timeType == 1) {//领券后N天可用
              couponInstructionArr = { returnString: "领券后" + availableTime.days + "天可用", timeString: [] }
            } else if (availableTime.timeType == 2) {//规则星期可用
              couponInstructionArr = pageHandleUtil.dillCouponWeek([], false, availableTime);
            }
            else if (availableTime.timeType == 3) {//规则日期可用
              console.log('availableTime.timeType === 3', availableTime.timeType === 3)
              couponInstructionArr = pageHandleUtil.dillCouponDay([], false, availableTime);
            }
            else if (availableTime.timeType == 4) {//不规则日期可用
              console.log('不规则日期可用')
              // couponInstructionArr = pageHandleUtil.dillCouponDay(availablePeriods);
              let timeString = pageHandleUtil.mToStrArray(availableTime);
              let returnString = availableTime.dateList.replace(/:/g, " ~ ");
              couponInstructionArr = { returnString: returnString, timeString: timeString }
            }
            // }
          } else {
            couponInstructionArr = { returnString: `全部时段可用`, timeString: `` };
          }
          this.setData({
            type: data.type == 'coupon' ? 1 : 2,
            couponInstructionArr,
            prototype,
            availableTime,
            showDetail: true,
            loading: false,
            receiveCode
          });
          let theme, colorTitle;
          if (prototype.theme) {
            theme = prototype.theme;
            console.log('prototype.theme', prototype.theme);
            console.log('theme.toLowerCase()', theme.toLowerCase());
            colorTitle = $color.getTitleColor(theme.toLowerCase());
          } else { theme = this.data.themeColor; colorTitle = this.data.themeTitleColor }
          console.log("theme", theme)
          this.setData({ theme, colorTitle })
          wx.setBackgroundColor({ backgroundColorTop: theme, backgroundColorBottom: theme });
        }
      })
    },
    //获取领取券展示信息
    getPrototypeInfoFunc() {
      let receiveCode = this.data.receiveCode;
      console.log('receiveCode', receiveCode)
      getPrototypeInfo(receiveCode).then(res => {
        console.log('res', res)
        if (res.code == 0) {
          let { availableTime, prototype } = res.data;
          // 时段可使用渲染
          let couponInstructionArr = {};
          //1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用，5：全时段可用
          if (availableTime && availableTime.timeType != 5) {

            //    if (availableTime.availablePeriod || availableTime.dateList) {
            console.log('availableTime.timeType', availableTime.timeType)
            if (availableTime.timeType == 1) {//领券后N天可用
              couponInstructionArr = { returnString: "领券后" + availableTime.days + "天可用", timeString: [] }
            } else if (availableTime.timeType == 2) {//规则星期可用
              couponInstructionArr = pageHandleUtil.dillCouponWeek([], false, availableTime);
            }
            else if (availableTime.timeType == 3) {//规则日期可用
              console.log('availableTime.timeType === 3', availableTime.timeType === 3)
              couponInstructionArr = pageHandleUtil.dillCouponDay([], false, availableTime);
            }
            else if (availableTime.timeType == 4) {//不规则日期可用
              console.log('不规则日期可用')
              // couponInstructionArr = pageHandleUtil.dillCouponDay(availablePeriods);
              let timeString = pageHandleUtil.mToStrArray(availableTime);
              let returnString = availableTime.dateList.replace(/:/g, " ~ ");
              couponInstructionArr = { returnString: returnString, timeString: timeString }
            }
            // }
          } else {
            couponInstructionArr = { returnString: `全部时段可用`, timeString: `` };
          }
          console.log('couponInstructionArr', couponInstructionArr)
          this.setData({
            couponInstructionArr,
            prototype,
            availableTime,
            showDetail: true,
            loading: false
          });
          let theme, colorTitle;
          if (prototype.theme) {
            theme = prototype.theme;
            console.log('prototype.theme', prototype.theme);
            console.log('theme.toLowerCase()', theme.toLowerCase());
            colorTitle = $color.getTitleColor(theme.toLowerCase());
          } else { theme = this.data.themeColor; colorTitle = this.data.themeTitleColor }
          console.log("theme", theme)
          this.setData({ theme, colorTitle })
          wx.setBackgroundColor({ backgroundColorTop: theme, backgroundColorBottom: theme });
        }
      })
    },
    //显示券详情
    showDetailFunc() {
      if ((this.data.type == 1 && this.data.couponStatus == 1 && this.data.model == 1) || (this.data.type == 2 && this.data.couponStatus == 1 && this.data.model == 1)) {
        this.setData({
          showDetail: true
        })
      }
    },
    //隐藏券详情
    hiddenDetailFunc() {
      if ((this.data.type == 1 && this.data.couponStatus == 1 && this.data.model == 1) || (this.data.type == 2 && this.data.couponStatus == 1 && this.data.model == 1)) {
        this.setData({
          showDetail: false
        })
      }

    },
    //领取优惠券
    receiveBizCouponNewFunc() {
      let self = this;
      let receiveCode = this.data.receiveCode
      receiveBizCouponNew(receiveCode).then(res => {
        if (res.code == 0) {
          let prototype = self.data.prototype;
          let params = res.data.params;
          let codes = res.data.codes;
          if (codes) {
            this.setData({
              couponCode: codes[0]
            })
          }
          if (res.data.finish) {
            wx.showToast({
              title: '领取成功',
              icon: 'success',
              duration: 2000
            })
            self.setData({
              model: 1,
            })
            self.couponDetailReq();
            //轮询去检查优惠券的状态
            if (this.data.type == 1) {
              if (!this.data.interTime) {
                let interTime = setInterval(() => {
                  this.couponStatusReq();
                }, 5000)
                this.setData({ interTime: interTime })
              }
            }
          } else {
            self.showReceiveCoupon(prototype, params, codes)
          }
        }

      })
    },
    toAllShopAvailable() {
      // let couponId = this.data.prototype.id;
      this.selectComponent("#shop-list-dialog").dialogShow({
        type: this.data.type,
        couponId: this.data.prototype.id
      });
    },
    //展示领取弹框
    showReceiveCoupon(prototype, params, codes) {
      this.selectComponent("#receiveCoupon").dialogShow(prototype, params, codes);
    },
    //监听是否需要刷新页面
    async getNowFunc() {
      await this.couponDetailReq();
      let interTime = setInterval(() => {
        this.couponStatusReq();
      }, 5000)
      this.setData({ interTime: interTime })

      //this.couponStatusReq()
      this.setData({
        model: 1,
        type: 1
      })

    },
    //显示按钮
    handleButtonConfig() {
      let prototype = this.data.prototype;
      let functionButtonConfig;
      if (prototype.functionButton && prototype.functionButtonConfig) {
        functionButtonConfig = JSON.parse(prototype.functionButtonConfig)
      };
      this.setData({ functionButtonConfig })
    },
    //显示时间
    handleTimeConfig() {
      let effectiveTime = this.data.effectiveTime;
      let expireTime = this.data.expireTime;
      if (effectiveTime) { effectiveTime = dayjs(effectiveTime).format('YYYY-MM-DD') };
      if (expireTime) { expireTime = dayjs(expireTime).subtract(1, "second").format('YYYY-MM-DD') };
      this.setData({
        effectiveTime,
        expireTime
      })
    },
    handleButton(e) {
      let appId = e.currentTarget.dataset.item.appId;
      let page = e.currentTarget.dataset.item.page;
      const accountInfo = wx.getAccountInfoSync();
      let nowAppId = accountInfo.miniProgram.appId;
      //本小程序appid
      if (nowAppId === appId) {
        router.push({ path: page })
      } else {//非本小程序appid
        wx.navigateToMiniProgram({
          appId: appId,
          path: page,
        })
      }
    },
    touchStart(e) {
      this.setData({
        touchX: e.changedTouches[0].clientX,
        touchY: e.changedTouches[0].clientY
      })
    },
    touchEnd(e) {
      let x = e.changedTouches[0].clientX;
      let y = e.changedTouches[0].clientY;
      console.log("type", this.data.type)
      console.log("status", this.data.couponStatus)
      console.log("model", this.data.model)
      if ((this.data.type == 1 && this.data.couponStatus == 1 && this.data.model == 1) || (this.data.type == 2 && this.data.couponStatus == 1 && this.data.model == 1)) {
        if (y - this.data.touchY > 20 && Math.abs(x - this.data.touchX) < 20) { //下滑
          this.setData({
            showDetail: false
          })
        } else if (y - this.data.touchY < -20 && Math.abs(x - this.data.touchX) < 20) { //上滑
          this.setData({
            showDetail: true
          })
        }
      }
    },
    //微信领取券的回调
    // updateCoupon(params) {
    //   console.log('发券结果', params);
    // },
    //检查券的状态
    couponStatusReq() {
      //券状态，1：正常，2：已使用，3：已过期，4：已锁定
      let data = {
        couponCode: this.data.couponCode
      };
      let self = this;
      getCouponStatus(data).then(res => {
        if (res.code === 0) {
          if (res.data.status === 2) {
            // 已经使用
            if (this.data.couponStatus === 1) {
              // 之前卡券状态为1的时候出来
              self.toSendFriend(res.data);
              this.couponDetailReq();
            }
            this.setData({
              verifyMerchant: res.data.verifyMerchant,
              verifyShop: res.data.verifyShop
            })
            this.clear();
          } else if (res.data.isExpired) {
            this.couponDetailReq();
            this.clear();
          }
        }
      })
    },
    handleCloseFinish() {
      this.setData({ haoDaModal: false })
    },
    //放大二维码功能
    enlargeFenc(e) {
      console.log('e', e)
      let img = e.currentTarget.dataset.img;
      let type = e.currentTarget.dataset.type;
      this.selectComponent("#enlargeImage").dialogShow(img, type);
    },
    clear() {
      // wx.setScreenBrightness({
      //   value: .4
      // })
      if (this.data.interTime) {
        clearInterval(this.data.interTime);
        this.setData({ interTime: null })
      }
    },
    // 弹出modal框
    toSendFriend(data) {
      wx.showModal({
        title: '提示',
        content: `您的${this.data.prototype.couponName}已经在${data.verifyMerchant}的 ${data.verifyShop} 被核销`,
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      this.setData({ sendFriendModal: true })
    },
    receiveCodeReq() {
      let data = { couponCode: this.data.couponDetail.couponCode }
      return getCouponReceiveCode(data).then(res => {
        if (res.code === 0) {
          this.setData({ receiveCode: res.data })
        }
      })
    },
    // 更改券的状态为赠送
    confirmGiveReq() {
      let data = {
        receiveCode: this.data.receiveCode
      };
      confirmGive(data).then(res => {
        if (res.code === 0) {
          this.couponDetailReq();
          this.clear();
        }
      })
    },
    syncConfigReq() {
      if (this.data.couponDetail.syncWx) {
        return;
      }
      let data = {
        couponCode: this.data.couponCode
      };
      wx.showLoading({ title: "同步中...", mask: true });
      getCouponSyncConfig(data).then(res => {
        setTimeout(() => {
          wx.hideLoading();
        }, 200)
        wx.addCard({
          cardList: [{ cardId: res.data.cardId, cardExt: res.data.cardExt }],
          success: (res) => {
            if (res.cardList[0].isSuccess) {
              this.couponDetailReq();
              wx.showToast({ title: "同步卡包成功", icon: "success", duration: 3000 });
            }
          }, cancel: (res) => {
            wx.showToast({ title: "您取消了同步卡包", icon: "none", duration: 4000 });
          },
          fail: (res) => {
            this.couponDetailReq();
            wx.showToast({ title: "同步卡包失败" + res, icon: "none", duration: 4000 });
          }
        });
      }).catch(() => {
        wx.hideLoading();
      })
    },
    couponGiveCancelReq() {
      // 取消赠送中的卡券
      let data = {
        couponCode: this.data.couponDetail.couponCode
      };
      cancelGive(data).then(res => {
        this.couponDetailReq();
      })
    },
    haoDaBtn() {
      // 好哒按钮
      getApp().$router.redirectTo({ name: 'member/myCoupon' })
    },
    useInstruction() {
      this.selectComponent("#use-instruction").open({
        passRemark: this.data.couponDetail.remark,
        couponInstructionArr: this.data.couponInstructionArr
      });
    },
    sendFriendMBtn() {
      // 好哒按钮
      this.setData({ sendFriendModal: false })
    },
    handleStop() {
      return false;
    },

    handleGenPoster(e) {
      this.setData({ "shareImg": e.detail })
    },
  }
})
